package com.cug.smartranch.animal.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.cug.smartranch.animal.admin.common.enums.FeedEquipmentStatusEnum;
import com.cug.smartranch.animal.admin.dao.entity.FeedDetail;
import com.cug.smartranch.animal.admin.dao.entity.FeedEquipment;
import com.cug.smartranch.animal.admin.dao.mapper.FeedDetailMapper;
import com.cug.smartranch.animal.admin.dao.mapper.FeedEquipmentMapper;
import com.cug.smartranch.animal.admin.dto.req.EquipmentSaveReqDTO;
import com.cug.smartranch.animal.admin.dto.req.FeedEquipmentPageQueryReqDTO;
import com.cug.smartranch.animal.admin.dto.resp.FeedEquipmentPageQueryRespDTO;
import com.cug.smartranch.animal.admin.service.FeedEquipmentService;
import com.cug.smartranch.framework.exception.ClientException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 喂养设备记录业务逻辑实现层
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class FeedEquipmentServiceImpl extends ServiceImpl<FeedEquipmentMapper, FeedEquipment> implements FeedEquipmentService {
    private final FeedEquipmentMapper feedEquipmentMapper;
    private final FeedDetailMapper feedDetailMapper;

    @Override
    public void createEquipment(EquipmentSaveReqDTO requestParam) {
        //参数判空校验
        if (Objects.isNull(requestParam)) {
            throw new ClientException("参数不能为空！");
        }
        if (StrUtil.isBlank(requestParam.getName())) {
            throw new ClientException("设备name不能为空");
        }
        if (StrUtil.isBlank(requestParam.getLocation())) {
            throw new ClientException("设备位置不能为空");
        }
        if (Objects.isNull(requestParam.getFeedCategory())) {
            throw new ClientException("饲料种类不能为空");
        }
        if (Objects.isNull(requestParam.getRemainFeedAmount())) {
            throw new ClientException("剩余饲料量不能为空");
        }
        if (Objects.isNull(requestParam.getStatus())) {
            throw new ClientException("设备启动状态不能为空！");
        }
        // 校验不能有重复设备名称
        LambdaQueryWrapper<FeedEquipment> queryWrapper = Wrappers.lambdaQuery(FeedEquipment.class);
        queryWrapper.eq(FeedEquipment::getName, requestParam.getName());
        FeedEquipment isExist = feedEquipmentMapper.selectOne(queryWrapper);
        if (Objects.nonNull(isExist)) {
            throw new ClientException("设备名称重复！");
        }
        // 创建设备记录
        FeedEquipment feedEquipMent = FeedEquipment.builder()
                .name(requestParam.getName())
                .location(requestParam.getLocation())
                .feedCategory(requestParam.getFeedCategory())
                .remainFeedAmount(requestParam.getRemainFeedAmount())
                .status(requestParam.getStatus())
                .updateStatusTime(new Date())
                .build();
        int insert = feedEquipmentMapper.insert(feedEquipMent);
        boolean flag = SqlHelper.retBool(insert);
        if (!flag) {
            throw new ClientException("创建设备记录异常！！");
        }
    }

    @Override
    public IPage<FeedEquipmentPageQueryRespDTO> selectAllFeedEquipment(FeedEquipmentPageQueryReqDTO requestParam) {
        Page<FeedEquipment> page = new Page<>(requestParam.getPageNo(), requestParam.getPageSize());
        Page<FeedEquipment> tempResult = feedEquipmentMapper.selectPage(page, null);
        IPage<FeedEquipmentPageQueryRespDTO> result = tempResult.convert(e -> {
            FeedEquipmentPageQueryRespDTO respDTO = new FeedEquipmentPageQueryRespDTO();
            respDTO.setName(e.getName());
            respDTO.setLocation(e.getLocation());
            respDTO.setFeedCategory(e.getFeedCategory());
            respDTO.setRemainFeedAmount(e.getRemainFeedAmount());
            respDTO.setStatus(e.getStatus());
            //设置设备运行时长
            if (Objects.equals(e.getStatus(), FeedEquipmentStatusEnum.STARTED.getType())) {
                long time = new Date().getTime() - e.getUpdateStatusTime().getTime();
                long hour = time / (1000 * 60 * 60);
                respDTO.setOperatingTime((int) hour);
            }
            //设置最近一次喂养时间
            LambdaQueryWrapper<FeedDetail> queryWrapper = Wrappers.lambdaQuery(FeedDetail.class);
            queryWrapper.eq(FeedDetail::getEquipmentName, e.getName());
            queryWrapper.orderByDesc(FeedDetail::getFeedTime);
            List<FeedDetail> list = feedDetailMapper.selectList(queryWrapper);
            if (!CollectionUtil.isEmpty(list)) {
                Date latestFeedTime = list.get(0).getFeedTime();
                respDTO.setLatestFeedTime(latestFeedTime);
            }
            return respDTO;
        });
        return result;
    }

    @Override
    public void enableOrClose(Integer status, Long id) {
        FeedEquipment feedEquipment = feedEquipmentMapper.selectById(id);
        if (Objects.isNull(feedEquipment)) {
            throw new ClientException("该设备不存在！");
        }
        if (!Objects.equals(feedEquipment.getStatus(), status)) {
            feedEquipment.setStatus(status);
            feedEquipment.setUpdateStatusTime(new Date());
            feedEquipmentMapper.updateById(feedEquipment);
        }
    }


}
